from selenium import webdriver
import time
import re
import pymysql.cursors

# connection = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='1940952395', db='tencent',
#                              charset='utf8', cursorclass=pymysql.cursors.DictCursor)
#
# cur = connection.cursor()


def serch():
    driver.find_element_by_id('q').send_keys('python')
    driver.find_element_by_class_name("btn-search").click()
    time.sleep(10)
    token = driver.find_element_by_xpath(
        '//*[@id="mainsrp-pager"]/div/div/div/div[@class="total"]').text
    token = int(re.compile('\d+').search(token).group(0))
    return token


def drop_down():
    for x in range(1, 11, 2):
        time.sleep(1.5)
        j = x / 10
        js = 'document.documentElement.scrollTop = document.documentElement.scrollHeight * %f' % j
        driver.execute_script(js)


def next_page():
    token = serch()
    num = 0
    while num != token-1:  # token-1
        driver.get(
            'https://s.taobao.com/search?q={}&s={}'.format(keyword, 44 * num))
        driver.implicitly_wait(10)
        num += 1
        drop_down()
        get_product()


def get_product():
    lis = driver.find_elements_by_xpath(
        '//div[@class="items"]/div[@class="item J_MouserOnverReq  "]')
    for li in lis:
        info = li.find_element_by_xpath(
            './/div[@class="row row-2 title"]').text
        price = li.find_element_by_xpath(
            './/div[@class="row row-1 g-clearfix"]/div[@class="price g_price g_price-highlight"]/strong').text
        image = li.find_element_by_xpath(
            './/div[@class="pic"]/a/img').get_attribute('src')
        name = li.find_element_by_xpath('.//div[@class="shop"]/a/span[2]').text
        shop = li.find_element_by_xpath(
            './/div[@class="row row-1 g-clearfix"]/div[2]').text
        adder = li.find_element_by_xpath('.//div[2]/div[3]/div[2]').text
        goods = {
            'name': info,
            'price': price,
            'image': image,
            'store': name,
            'shop': shop,
            'adder': adder
        }
        print(goods)
        # sql = "insert into goods(name,price,image,store,shopnum,adder)values (%s,%s,%s,%s,%s,%s)"
        # params = (goods["name"], goods["price"], goods["image"],
        #           goods["store"], goods["shop"], goods["adder"])
        # cur.execute(sql, params)
        # connection.commit()


if __name__ == '__main__':
    keyword = input('请输入您要商品信息:')
    driver = webdriver.Chrome()
    driver.get('http:www.taobao.com')
    # next_page()
    # cur.close()
    # connection.close()
